package com.dragon8869.myspringboot.quartz;

import com.dragon8869.myspringboot.entity.AyUser;
import com.dragon8869.myspringboot.service.AyUserService;
import com.dragon8869.myspringboot.service.MailService;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@Component
@Configuration
@Log4j2
@EnableScheduling
public class SendMailQuartz {

    @Resource
    AyUserService ayUserService;

    @Resource
    MailService mailService;

    @Scheduled(cron = "*/5 * * * * *")
    public void reportCurrentByCron(){
        log.info(this + "定时器运行了");
//        sendMail();
    }

    public void sendMail(){
        List<AyUser> ayUsers = ayUserService.findAll();
        for (int index = ayUsers.size() - 1; index >= 0; index--) {
            if (!StringUtils.hasLength(ayUsers.get(index).getEmail())){
                ayUsers.remove(index);
            }
        }
        try {
            mailService.sendMail(ayUsers);
            log.info("邮件发送成功");
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("邮件发送成功", e);
        }

    }

    @Override
    public String toString() {
        return "SendMailQuartz{}";
    }
}
